package cn.flightcloud.auth.config.spring.security.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import cn.flightcloud.auth.config.spring.security.SecurityUser;

/**
 * 该UserDetailsService实现需要自行实现
 * 
 * @author chenjj
 *
 */
public class SimpleUserDetailsService implements UserDetailsService {
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 这里需要从后台查询用户信息
		if (StringUtils.isEmpty(username)) {
			throw new UsernameNotFoundException("username not found");
		}
		SecurityUser userDetails = new SecurityUser();
		// if (userDetails == null) {
		// throw new UsernameNotFoundException("username " + username + " not
		// found");
		// }
		userDetails.setUsername(username);
		userDetails.setAccountNonExpired(true);
		userDetails.setAccountNonLocked(true);
		userDetails.setCredentialsNonExpired(true);
		userDetails.setEnabled(true);
		userDetails.setPassword(passwordEncoder.encode(username));
		List<GrantedAuthority> list = new ArrayList<>();
		if ("admin".equals(username)) {
			SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
			list.add(simpleGrantedAuthority);
			userDetails.setAuthorities(list);
		}
		return userDetails;
	}

}
